<?php

namespace app\admin\model;

use think\Model;
use app\admin\model\AdminLog;

class Admin extends Model {
    //

    /**
     * 登录
     * @param type $email
     * @param type $password
     * @return type
     */
    public function login($email = '', $password = '') {
        $log = new AdminLog(); //日志模型
        $check = $this->where('email', $email)->find();
        if (empty($check)) {
            $log->loginLog(0, $email, '用户不存在');
            return fail('用户不存在');
        }

        if ($check->status != 1) {
            $log->loginLog($check->id, $check->username, '账户已被锁定，请联系系统管理员');
            return fail('账户已被锁定，请联系系统管理员！');
        }

        $checkPassword = md5($password . $check['salt']);
        if ($checkPassword !== $check['password']) {
            $log->loginLog($check->id, $check->username, '密码错误');
            $check->loginfailure++;
            $check->updated_at = time();
            if ($check->loginfailure >= 5) {
                $check->status = 0;
            }
            $check->save();
            if ($check->loginfailure > 2) {
                return fail('密码错误,错误次数超过5次，账号将被锁定！');
            } else {
                return fail('密码错误');
            }
        }

        $log->loginLog($check->id, $check->username, '成功');
        $check->loginfailure = 0;
        $check->logintime = time();
        $check->token = session_id();
        $check->save();
        return success($check->toArray());
    }


    /**
     * 校验邮件是否唯一
     * @param type $email
     * @param type $adminid
     * @return boolean
     */
    public function checkEmailUnique($email, $adminid = 0) {
        $check = $this->where('email', $email)->find();
        if (empty($check)) {
            return true;
        }

        if ($adminid == $check->id) {
            return true;
        }

        return false;
    }

}
